import React, {useState, useEffect} from 'react';
import {Button, notification, Table} from "antd";
import axios from "axios";
import {InfoCircleOutlined} from '@ant-design/icons';
import './PublishTable.css'

export default function PublishTable(props) {

    const [dataSource,setDataSource] = useState([])

    const {username} = JSON.parse(localStorage.getItem('token'))

    useEffect(() => {
        axios.get(`/news?author=${username}&publishState=${props.publishState}&_expand=category`).then(res => {
            console.log(res.data)
            setDataSource(res.data)
        })
    },[username,props.publishState])

    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'title',
            render: (title, item) => {
                return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
            }
            // todo=>限制该列宽
        },
        {
            title: '作者',
            dataIndex: 'author',
        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            render: (category) => {
                return category.title
            }
        },
        {
            title: '操作',
            render: (item) => {
                return <div className='noselect'>
                    <Button style={props.buttonStyle} type="primary" size={"small"} danger={props.danger} onClick={() => {
                        handleRevoke(item,props.publishState)
                    }}>{props.buttonText}</Button>
                </div>
            }
        },
    ]

    const handleRevoke = (item,publishState) => {
        setDataSource(dataSource.filter(data => data.id !== item.id))
        if (publishState <= 2){
            axios.patch(`/news/${item.id}`,{
                publishState: publishState+1
            }).then(() => {
                if (publishState === 1){
                    notification.success({
                        message: '恭喜您！',
                        description:
                            `新闻【${item.title}】发表成功`
                    })
                }else {
                    notification.warning({
                        message: '通知',
                        description:
                            `新闻【${item.title}】下线成功`
                    })
                }
            })
        }else {
            axios.delete(`/news/${item.id}`).then(() => {
                notification.info({
                    icon: <InfoCircleOutlined />,
                    className: 'myerrorColor',
                    message: '通知',
                    description:
                        `新闻【${item.title}】已删除`
                })
            })
        }
    }

    return (
        <div>
            <Table dataSource={dataSource} columns={columns}
                   rowKey={item => item.id}/>
        </div>
    )
}